// vim: set et sw=4 ts=4 sts=4 fdm=marker ff=unix fenc=utf8 nobomb:
/**
 * Tweets Manager
 *      based on HTML5 Database
 *
 * @author mingcheng<i.feelinglucky#gmail.com>
 * @since  2010-01-02
 * @link   http://www.gracecode.com/
 */

void function(scope) {
    var Y = YAHOO, Lang = Y.lang;

    var config = {
        username: null
    },database = null, sql = "";

    // default table scruct
    var defTableStruct = [
        "_id INTEGER PRIMARY KEY AUTOINCREMENT",
        "created_at TEXT", 
        "favorited TEXT",
        "geo TEXT",
        "id REAL UNIQUE", 
        "in_reply_to_screen_name TEXT", 
        "in_reply_to_status_id REAL", 
        "in_reply_to_user_id REAL",
        "retweeted_status TEXT",
        "sender_id REAL",
        "sender_name TEXT",
        "sender_profile_image_url TEXT", 
        "sender_screen_name TEXT",
        "source TEXT",
        "text TEXT", 
        "truncated INTEGER"
     ].join(", "),
     // each tables structure
     tables = {
         'home': defTableStruct,
         'friends': defTableStruct,
         'mentions': defTableStruct,
         'favourite': defTableStruct,
         'direct': [
             "_id INTEGER PRIMARY KEY AUTOINCREMENT",
             "created_at TEXT", 
             "id REAL UNIQUE", 
             "in_reply_to_screen_name TEXT",
             "recipient_id REAL",
             "recipient_screen_name TEXT",
             "truncated TEXT",
             "sender_id REAL",
             "sender_screen_name TEXT",
             "source TEXT",
             "text TEXT"
         ].join(", "),
         'user': [
             "_id INTEGER PRIMARY KEY AUTOINCREMENT",
             "created_at TEXT", 
             "description TEXT", 
             "favourites_count INTEGER", 
             "followers_count INTEGER", 
             "following TEXT", 
             "friends_count INTEGER", 
             "geo_enabled TEXT", 
             "id REAL UNIQUE", 
             "location TEXT", 
             "name TEXT", 
             "notifications TEXT", 
             "profile_background_color TEXT", 
             "profile_background_image_tile TEXT", 
             "profile_background_image_url TEXT", 
             "profile_image_url TEXT", 
             "profile_link_color TEXT", 
             "profile_sidebar_border_color TEXT", 
             "profile_sidebar_fill_color TEXT", 
             "profile_text_color TEXT", 
             "protected TEXT", 
             "screen_name TEXT",
             "statuses_count REAL",
             "time_zone TEXT",
             "url TEXT",
             "utc_offset TEXT",
             "verified TEXT"
        ].join(", ")
    };

    // create table if not exists
    var initDatabase = function(tx) {
        for (table in tables) {
            sql = "CREATE TABLE IF NOT EXISTS " + table + " (" + tables[table] + ");";
            tx.executeSql(sql);
        }

        // create database index
        // ...
    };

    /**
     * open database
     */
    var openDatabase = function() {
        if (!config.username || !/^[a-z]+/i.test(config.username)) {
            console.error("username '"+ config.username +"' is illegal");
            return;
        }

        if (window.openDatabase) {
            database = window.openDatabase(config.username, "1.0", "Storage tweets for " + config.username);
            if (!database) {
                throw error('open database error, try to update the newest version of chromium.');
            }

            // test database
            database.transaction(function(tx) {
                // join all created tables
                var tmp = [];
                for (table in tables) {
                    tmp.push(table);
                }

                tx.executeSql("SELECT COUNT(*) FROM " + tmp.join(", "),
                    undefined,  // data
                    undefined,  // callback when success
                    function(tx, error) {
                        console.warn('database: tables seens not exists, try to create them');
                        initDatabase(tx);
                    } // callback when error
                );
            });
        } else {
            throw error("your chormium don't support HTML5 database, " + 
                    " Please try to update the newest version of chromium.");
        }
    }; // open database

    var Query = {
        insert: function(table, data, callback) {
            var fields = [], values = [], flags = [], sql = '';

            // bulid query string
            for(field in data) {
                if (Lang.isString(field) && field.length) {
                    fields.push(field);
                    values.push(data[field]);
                    flags.push('?');
                }
            }

            // sql insert
            sql = 'INSERT INTO ' + table + '('+ fields.join(', ') +') VALUES ('+ flags.join(', ') +')';

            // start trans action
            database.transaction(function (tx) {
                tx.executeSql(sql, values, callback.onSuccess || undefined, callback.onError || undefined);
            });
        },

        update: function(table, data, callback) {
            // start trans action
            database.transaction(function (tx) {
                tx.executeSql(sql, values, callback.onSuccess || undefined, callback.onError || undefined);
            });
        },

        del: function(table, id, callback) {
            // start trans action
            database.transaction(function (tx) {
                sql = 'DELETE FROM '+ table +' WHERE id=' + id
                tx.executeSql(sql, [], callback.onSuccess || undefined, callback.onError || undefined);
            });
        }
    };

    var deleteTweet = function() {
    
    };

    scope.Tweets = {
        /**
         * addTweet
         *      insert one tweet data into database
         *
         * @param name String
         * @param data Object 
         * @param callback Object 
         */
        addTweet: function(name, data, callback, persist) {
            if (persist && data.id) {
                this.deleteTweets(name, data.id, {
                    onSuccess: function(tx) {
                        Query.insert(name, data, callback || {});
                    },
                    onError: function(tx, error) {
                        console.error('database: ' + error.message);
                    }
                });

                return;
            }
            Query.insert(name, data, callback || {});
        },

        /**
         * addMultiTweets
         *     insert multi-tweets data into database
         *
         * @param name String
         * @param data Array
         * @param callback Object
         */
        addMultiTweets: function(name, data, callback) {
            callback = callback || {};
            if (Lang.isArray(data)) {
                for(var i = 0, len = data.length; i < len; i++) {
                    this.addTweet(name, data[i], callback);
                }
            } else {
                this.addTweet(name, data, callback);
            }
        },

        /**
         * addUser
         *     insert userInfo into database
         *
         */
        addUser: function(data, callback) {
            Query.insert('user', data, callback || {});
        },

        deleteTweets: function(name, id, callback) {
            Query.del(name, id, callback || {});
        },

        getTweetsList: function(name, limit, callback) {
            callback = callback || {};
        
            /*
    tx.executeSql("SELECT id, note, timestamp, left, top, zindex FROM WebKitStickyNotes", 
        [], function(tx, result) {
            */
        
        },

        getUser: function(name, data, callback) {
            callback = callback || {};
        
        },

        getTweet: function(name, id, callback) {
            callback = callback || {};

        },

        updateTweets: function(name, id, data, callback) {
            callback = callback || {};
            /*
    tx.executeSql("UPDATE WebKitStickyNotes SET " +
        "note = ?, timestamp = ?, left = ?, top = ?, zindex = ? " +
        " WHERE id = ?", 
        */

        
        },

        updateUser: function(username, data, callback) {
            callback = callback || {};

        },

        setConfig: function(user_config) {
            YAHOO.lang.augmentObject(config, user_config, true);
        },

        openDatabase: openDatabase,

        truncateTables: function(callback) {
            callback = callback || {};
            for(table in tables) {
                database.transaction(function (tx) {
                    tx.executeSql('DELETE FROM `'+ table + '`', [], 
                        callback.onSuccess || undefined, callback.onError || undefined);
                });
            }
        }
    };
}(this);
